package com.goktech.olala.client.controller.backstage;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.goktech.olala.client.controller.basic.BasicController;
import com.goktech.olala.client.controller.basic.ResultStatus;
import com.goktech.olala.core.config.SysConfig;
import com.goktech.olala.core.req.ReqCtmInfo;
import com.goktech.olala.core.req.ReqCtmLevel;
import com.goktech.olala.core.req.ReqCtmLogin;
import com.goktech.olala.core.resp.RespCtmLogin;
import com.goktech.olala.core.resp.RespCtmInfo;
import com.goktech.olala.core.service.ICtmInfoService;
import com.goktech.olala.server.pojo.customer.CtmLevelInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author wusq
 * 会员信息控制层
 */

@Controller
@RequestMapping(value = "/memberApi")
public class MemberController extends BasicController {

    @Autowired
    ICtmInfoService ctmInfoService;


    /**
     * 会员信息查询
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryMembers.do", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap queryMembers(HttpServletRequest request, Integer sEcho,
                                 Integer iDisplayStart, Integer iDisplayLength) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "";

        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            ReqCtmInfo ctmInfoReq = buildCtmInfo(params);
            int pageIndex = iDisplayStart / iDisplayLength + 1;
            PageInfo<RespCtmInfo> pageInfo = ctmInfoService.queryCmtInfoByExample(pageIndex, iDisplayLength, ctmInfoReq);
            if (pageInfo != null && CollectionUtils.isEmpty(pageInfo.getList())) {
                respCode = -10000;
                respMsg = "查询结果集为空!";
            }
            respData = super.respParamsFormat(respCode, respMsg, sEcho, pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = SysConfig.ERROR_CODE;
            respMsg = e.getMessage();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }

    /**
     * 会员信息查询
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryMembersById.do", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap queryMembersById(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "";

        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            String customerInfId = params.getString("customerInfId");
            String customerId = params.getString("customerId");
            if (StringUtils.isBlank(customerInfId) && StringUtils.isBlank(customerId)) {
                respCode = ResultStatus.BAD_PARAM_REQUEST.getCode();
                respMsg = ResultStatus.BAD_PARAM_REQUEST.getMsg();

                respData = super.respParamsFormat(respCode, respMsg, null);
                resultMap.put("respData", respData);
                return resultMap;
            }
            RespCtmInfo respCtmInfo = ctmInfoService.queryCustomerInfoById(customerInfId, customerId);
            if (respCtmInfo == null) {
                respCode = ResultStatus.QUERY_NULL.getCode();
                respMsg = ResultStatus.QUERY_NULL.getMsg();
            }
            respData = super.respParamsFormat(respCode, respMsg, respCtmInfo);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = SysConfig.ERROR_CODE;
            respMsg = e.getMessage();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }

    /**
     * 新增会员信息
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/saveMember.do")
    @ResponseBody
    public ModelMap saveMember(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "保存成功!";

        JSONObject respData = new JSONObject();
        int result = 0;
        try {
            JSONObject params = super.reqParamsFormat(request);
            ReqCtmInfo ctmInfoReq = buildCtmInfo(params);
            RespCtmLogin ctmLoginVo = ctmInfoService.saveCmtInfo(ctmInfoReq);
            if(ctmLoginVo != null){
                result = 1;
            }
            respData = super.respParamsFormat(respCode, respMsg, result);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = SysConfig.ERROR_CODE;
            respMsg = e.getMessage();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }

    /**
     * 删除会员信息（物理删除）
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "removeMember.do")
    @ResponseBody
    public ModelMap removeMember(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "删除成功!";

        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            String customerInfId = params.getString("customerInfId");
            if (StringUtils.isBlank(customerInfId)) {
                respCode = -10002;
                respMsg = "customerInfId输入参数错误！";

                respData = super.respParamsFormat(respCode, respMsg, null);
                resultMap.put("respData", respData);
                return resultMap;
            }
            int result = ctmInfoService.removeCmtInfoById(customerInfId);
            respData = super.respParamsFormat(respCode, respMsg, result);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = SysConfig.ERROR_CODE;
            respMsg = e.getMessage();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }

    /**
     * 批量删除会员信息（物理删除）
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "removeMemberBatch.do")
    @ResponseBody
    public ModelMap removeMemberBatch(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "";

        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            String customerInfIds = params.getString("customerInfIds");
            String isDelStr = params.getString("isDel");
            if (StringUtils.isBlank(customerInfIds) || StringUtils.isBlank(isDelStr)) {
                respCode = ResultStatus.BAD_PARAM_REQUEST.getCode();
                respMsg = ResultStatus.BAD_PARAM_REQUEST.getMsg();

                respData = super.respParamsFormat(respCode, respMsg, null);
                resultMap.put("respData", respData);
                return resultMap;
            }
            int result = 0;
            String[] idArr = customerInfIds.split(",");
            result = ctmInfoService.removeCmtInfoByIdBatch(idArr);
            if(result > 0){
                respMsg = "批量删除成功,共删除"+idArr.length+"条数据!";
            }
            respData = super.respParamsFormat(respCode, respMsg, result);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = SysConfig.ERROR_CODE;
            respMsg = e.getMessage();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }

    /**
     * 修改会员删除状态
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "modifyDelStatusById.do")
    @ResponseBody
    public ModelMap modifyDelStatusById(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "删除成功!";

        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            String customerInfId = params.getString("customerInfId");
            Integer isDel = params.getInteger("isDel");
            if (StringUtils.isBlank(customerInfId) || isDel == null) {
                respCode = ResultStatus.BAD_PARAM_REQUEST.getCode();
                respMsg = ResultStatus.BAD_PARAM_REQUEST.getMsg();

                respData = super.respParamsFormat(respCode, respMsg, null);
                resultMap.put("respData", respData);
                return resultMap;
            }
            int result = ctmInfoService.updateDelStatusById(customerInfId, isDel);
            respData = super.respParamsFormat(respCode, respMsg, result);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = SysConfig.ERROR_CODE;
            respMsg = e.getMessage();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }

    /**
     * 批量修改会员删除状态信息
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "modifyDelStatusByIdBatch.do")
    @ResponseBody
    public ModelMap modifyDelStatusByIdBatch(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "";

        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            String customerInfIds = params.getString("customerInfIds");
            String isDelStr = params.getString("isDel");
            if (StringUtils.isBlank(customerInfIds) || StringUtils.isBlank(isDelStr)) {
                respCode = ResultStatus.BAD_PARAM_REQUEST.getCode();
                respMsg = ResultStatus.BAD_PARAM_REQUEST.getMsg();

                respData = super.respParamsFormat(respCode, respMsg, null);
                resultMap.put("respData", respData);
                return resultMap;
            }
            int result = 0;
            String[] idArr = customerInfIds.split(",");
            result = ctmInfoService.updateDelStatusByIdBatch(idArr, Integer.valueOf(isDelStr));
            if(result > 0){
               respMsg = "批量删除成功,共删除"+idArr.length+"条数据!";
            }
            respData = super.respParamsFormat(respCode, respMsg, result);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = SysConfig.ERROR_CODE;
            respMsg = e.getMessage();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }

    /**
     * 修改会员状态
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "updateMemberStatus.do")
    @ResponseBody
    public ModelMap updateMemberStatus(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "保存成功!";
        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            String customerInfId = params.getString("customerInfId");
            Integer status = params.getInteger("status");
            if (StringUtils.isBlank(customerInfId) && status == null) {
                respCode = ResultStatus.BAD_PARAM_REQUEST.getCode();
                respMsg = ResultStatus.BAD_PARAM_REQUEST.getMsg();

                respData = super.respParamsFormat(respCode, respMsg, null);
                resultMap.put("respData", respData);
                return resultMap;
            }
            int result = ctmInfoService.updateCmtStatus(customerInfId, status);
            respData = super.respParamsFormat(respCode, respMsg, result);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = SysConfig.ERROR_CODE;
            respMsg = e.getMessage();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }

    /**
     * 修改会员密码
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "updateMemberPwd.do")
    @ResponseBody
    public ModelMap updateMemberPwd(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "密码修改成功!";
        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            String customerId = params.getString("customerId");
            String newPassword = params.getString("newPassword");
            if (StringUtils.isBlank(customerId)) {
                respCode = ResultStatus.BAD_PARAM_REQUEST.getCode();
                respMsg = ResultStatus.BAD_PARAM_REQUEST.getMsg();

                respData = super.respParamsFormat(respCode, respMsg, null);
                resultMap.put("respData", respData);
                return resultMap;
            }
            int result = ctmInfoService.updateCmtPwd(customerId, newPassword);
            respData = super.respParamsFormat(respCode, respMsg, result);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = SysConfig.ERROR_CODE;
            respMsg = e.getMessage();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }

    /*=====================================会员等级=====================================*/

    /**
     * 会员等级管理-查询会员级别与该级别所需积分
     */
    @RequestMapping(value = "queryMemberLevel.do", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap queryMemberLevel(HttpServletRequest request, Integer sEcho,
                                     Integer iDisplayStart, Integer iDisplayLength) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "查询成功!";
        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            ReqCtmLevel reqCtmLevel = buildLevel(params);

            int pageIndex = iDisplayStart / iDisplayLength + 1;
            PageInfo<CtmLevelInfo> pageInfo = ctmInfoService.queryCtmLevel(pageIndex, iDisplayLength, reqCtmLevel);

            if (pageInfo != null && CollectionUtils.isEmpty(pageInfo.getList())) {
                respCode = ResultStatus.QUERY_NULL.getCode();
                respMsg = ResultStatus.QUERY_NULL.getMsg();
            }
            respData = super.respParamsFormat(respCode, respMsg, sEcho, pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = SysConfig.ERROR_CODE;
            respMsg = e.getMessage();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }

    /**
     * 根据ID查询会员信息
     */
    @RequestMapping(value = "queryLevelById.do")
    @ResponseBody
    public ModelMap queryLevelById(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "查询成功!";

        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            Integer customerLevelId = params.getInteger("customerLevelId");
            if (customerLevelId == null) {
                respCode = ResultStatus.BAD_PARAM_REQUEST.getCode();
                respMsg = ResultStatus.BAD_PARAM_REQUEST.getMsg();

                respData = super.respParamsFormat(respCode, respMsg, null);
                resultMap.put("respData", respData);
                return resultMap;
            }
            CtmLevelInfo ctmLevelInfo = ctmInfoService.queryCtmlevelById(customerLevelId);

            if (ctmLevelInfo == null) {
                respCode = ResultStatus.QUERY_NULL.getCode();
                respMsg = ResultStatus.QUERY_NULL.getMsg();
            }

            respData = super.respParamsFormat(respCode, respMsg, ctmLevelInfo);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = SysConfig.ERROR_CODE;
            respMsg = e.getMessage();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }

    /**
     * 添加会员等级
     */
    @RequestMapping(value = "saveLevelInfo.do")
    @ResponseBody
    public ModelMap saveLevelInfo(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "保存成功!";
        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            ReqCtmLevel reqCtmLevel = buildLevel(params);
            int result = ctmInfoService.saveCmtLevelInfo(reqCtmLevel);
            respData = super.respParamsFormat(respCode, respMsg, result);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = SysConfig.ERROR_CODE;
            respMsg = e.getMessage();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }

    /**
     * 删除会员等级
     */
    @RequestMapping(value = "removeLevelById.do")
    @ResponseBody
    public ModelMap removeLevelById(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "删除成功!";
        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            Integer customerLevelId = params.getInteger("customerLevelId");

            if (customerLevelId == null) {
                respCode = ResultStatus.BAD_PARAM_REQUEST.getCode();
                respMsg = ResultStatus.BAD_PARAM_REQUEST.getMsg();

                respData = super.respParamsFormat(respCode, respMsg, null);
                resultMap.put("respData", respData);
                return resultMap;
            }
            int result = ctmInfoService.removeLevelById(customerLevelId);
            respData = super.respParamsFormat(respCode, respMsg, result);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = SysConfig.ERROR_CODE;
            respMsg = e.getMessage();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }



    /*=====================================登陆日志=====================================*/

    /**
     * 查询用户登陆信息
     */
    @RequestMapping(value = "queryLoginLog.do", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap queryLoginLog(HttpServletRequest request, Integer sEcho,
                                        Integer iDisplayStart, Integer iDisplayLength) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "查询成功!";
        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            ReqCtmLogin reqCtmLogin = buildLoginLog(params);

            int pageIndex = iDisplayStart / iDisplayLength + 1;

            PageInfo<RespCtmLogin> pageInfo = ctmInfoService.queryCtmLoginLog(pageIndex, iDisplayLength, reqCtmLogin);

            if (pageInfo != null && CollectionUtils.isEmpty(pageInfo.getList())) {
                respCode = ResultStatus.QUERY_NULL.getCode();
                respMsg = ResultStatus.QUERY_NULL.getMsg();
            }
            respData = super.respParamsFormat(respCode, respMsg, sEcho, pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = SysConfig.ERROR_CODE;
            respMsg = e.getMessage();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }

    /*=====================================查询实体类=====================================*/

    /**
     * 构建会员等级查询实体类
     */
    private ReqCtmLevel buildLevel(JSONObject params) {
        return JSONObject.toJavaObject(params,ReqCtmLevel.class);
        /*ReqCtmLevel reqCtmLevel = new ReqCtmLevel();
        Integer customerLevelId = params.getInteger("customerLevelId");
        String levelName = params.getString("levelName");
        String beginTime = params.getString("beginTime");
        String endTime = params.getString("endTime");
        Integer levelStatus = params.getInteger("levelStatus");
        Integer minPoint = params.getInteger("minPoint");
        Integer maxPoint = params.getInteger("maxPoint");

        reqCtmLevel.setCustomerLevelId(customerLevelId);
        reqCtmLevel.setLevelName(levelName);
        reqCtmLevel.setBeginTime(beginTime);
        reqCtmLevel.setEndTime(endTime);
        reqCtmLevel.setLevelStatus(levelStatus);
        reqCtmLevel.setMinPoint(minPoint);
        reqCtmLevel.setMaxPoint(maxPoint);

        return reqCtmLevel;*/
    }

    /**
     * 登陆日志查询实体类
     */
    private ReqCtmLogin buildLoginLog(JSONObject params) {
        ReqCtmLogin reqCtmLogin = new ReqCtmLogin();
        String customerId = params.getString("customerId");
        String userInfo = params.getString("userInfo");
        String beginTime = params.getString("beginTime");
        String endTime = params.getString("endTime");

        reqCtmLogin.setCustomerId(customerId);
        reqCtmLogin.setUserInfo(userInfo);
        reqCtmLogin.setBeginTime(beginTime);
        reqCtmLogin.setEndTime(endTime);
        return reqCtmLogin;
    }

    /**
     * 构建查询实体类
     *
     * @param params
     * @return
     */
    private ReqCtmInfo buildCtmInfo(JSONObject params) {
        ReqCtmInfo ctmInfoReq = new ReqCtmInfo();
        String customerStatus = params.getString("customerStatus");
        String customerId = params.getString("customerId");
        String birthday = params.getString("birthday");
        String customerInfId = params.getString("customerInfId");
        String customerLevel = params.getString("customerLevel");
        String customerName = params.getString("customerName");
        String realName = params.getString("realName");
        String email = params.getString("email");
        String city = params.getString("city");
        String remark = params.getString("remark");
        String gender = params.getString("gender");
        String identyCardNo = params.getString("identyCardNo");
        String identyCardType = params.getString("identyCardType");
        String userBalance = params.getString("userBalance");
        String userMobile = params.getString("userMobile");
        String userPoint = params.getString("userPoint");
        String isDel = params.getString("isDel");
        String userInfo = params.getString("userInfo");

        ctmInfoReq.setCustomerInfId(customerInfId);
        ctmInfoReq.setCustomerId(customerId);
        ctmInfoReq.setCustomerName(customerName);
        ctmInfoReq.setRealName(realName);
        ctmInfoReq.setEmail(email);
        ctmInfoReq.setGender(gender);
        ctmInfoReq.setIdentyCardType(identyCardType);
        ctmInfoReq.setIdentyCardNo(identyCardNo);
        ctmInfoReq.setBirthday(birthday);
        ctmInfoReq.setCustomerLevel(customerLevel);
        ctmInfoReq.setCustomerStatus(customerStatus);
        ctmInfoReq.setUserBalance(userBalance);
        ctmInfoReq.setUserMobile(userMobile);
        ctmInfoReq.setUserPoint(userPoint);
        ctmInfoReq.setCity(city);
        ctmInfoReq.setRemark(remark);
        if(StringUtils.isNotBlank(userInfo)){
            ctmInfoReq.setUserInfo("%"+userInfo.trim()+"%");
        }
        if (StringUtils.isNotBlank(isDel)) {
            ctmInfoReq.setIsDel(Integer.valueOf(isDel));
        }
        return ctmInfoReq;
    }

}
